// 创建websocket 链接
/**
 * eg https = http+ssl
 * wss = ws+ssl
 */
// 链接状态 
let socketOpen = false
// 心跳检测状态
let xinTiao = true
// 链接失败情况下 发送的数据
let socketMsgQueue = []

import { useMessageStore } from "../stores/message"

function connect() {
	const MsgStore = useMessageStore()
	return new Promise((resolve, reject) => {
		uni.connectSocket({
			url: 'ws://127.0.0.1:3000'
		});

		// 链接成功后调用的钩子
		uni.onSocketOpen(function(res) {
			console.log("链接成功！！")
			socketOpen = true
			xinTiao = true
			let xinTiaoInv = setInterval(() => {
				if (xinTiao) {
					xinTiao = false
					sendSocketMessage({
						type: 'ping'
					})
				} else {
					// 链接状态 改成失败
					socketOpen = false
					// 把心跳关掉
					clearInterval(xinTiaoInv)
					xinTiaoInv = null
					repeatConnect()
				}
			}, 5000)
			resolve(true)
		});

		// 服务端给我们发送的内容调用的方法
		uni.onSocketMessage(function(res) {
			let data = JSON.parse(res.data)
			if (data.type === "pong") {
				xinTiao = true
			}else{
				console.log('收到服务器内容：' + res.data);
				// console.log(MsgStore.setWsData,52)
				MsgStore.setWsData(data)
			}
		});

		// 链接失败 调用的方法
		uni.onSocketError(function(res) {
			resolve(false)
		});

	})
}

async function repeatConnect() {

	while (!socketOpen) {

		let tempFlag = await connect()
		console.log("tempFlag", tempFlag)
		if (tempFlag) {
			break;
		}
		await wait(10)
	}



}

function wait(n) {
	return new Promise((res, rej) => {
		setTimeout(() => {
			res()
		}, n * 1000)
	})
}
// 我们向服务端推送消息的方法
function sendSocketMessage(msg) {
	
	if (socketOpen) {
		uni.sendSocketMessage({
			data: JSON.stringify(msg)
		});
	} else {
		socketMsgQueue.push(msg);
	}
}
export {
	connect,
	sendSocketMessage
}